<?php
/**
 * 申领单类
 * @package  htdocs
 * @subpackage  module/company
 * @author   create by allen.qiang
 * @version 1.0
 */

class cardApply{

    public function search( &$arg_array ){
        //加载用户部门类
        quanli_require('module/base/system/sysDepartment.class.php');

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申请编号
        if ( isset($arg_array['apply_id']) && is_numeric($arg_array['apply_id']) ) {
            $sql .= ' AND card_apply.apply_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['apply_id'];
        }

        //客户名称
        if ( isset($arg_array['customer_name']) && !empty($arg_array['customer_name']) ) {
            $sql .= ' AND card_apply.customer_name LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['customer_name'].'%';
        }

        //申领人
        if ( isset($arg_array['apply_user_id']) && !empty($arg_array['apply_user_id']) ) {
            $sql .= ' AND card_apply.apply_user_id = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['apply_user_id'] );
        }

        //申请状态
        if ( isset($arg_array['status']) && $arg_array['status']!="" ) {
            $sql .= ' AND card_apply.status = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['status'] );
        }

        //开票状态
        if ( isset($arg_array['invoice_status']) && $arg_array['invoice_status']!="" ) {
            $sql .= ' AND card_apply.invoice_status = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['invoice_status'] );
        }

        //回款状态
        if ( isset($arg_array['returned_money_status']) && $arg_array['returned_money_status']!="" ) {
            $sql .= ' AND card_apply.returned_money_status = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['returned_money_status'] );
        }

        //申请现金卡金额
        if ( isset($arg_array['total_amount']) && !empty($arg_array['total_amount']) ) {
            $sql .= ' AND card_apply.total_amount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['total_amount'];
        }


        //部门ID
        if (isset($arg_array['departmentID']) && !empty($arg_array['departmentID']) && $arg_array['departmentID']!="") {
           /* $sql .= ' AND departmentID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['departmentID'];*/
            $sql .= ' AND card_apply.departmentID in ('.$arg_array['departmentID'].')';

        }

        //部门名称
        if (isset($arg_array['departmentName']) && !empty($arg_array['departmentName'])) {
            $sql .= ' AND card_apply.departmentName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['departmentName']) . '%';
        }

        //创建开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND card_apply.apply_date >=?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] ;
        }
        //结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND card_apply.apply_date <=?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] ;
        }

        //是否删除
        if (isset($arg_array['is_delete']) && !empty($arg_array['is_delete'])) {
            $sql .= ' AND card_apply.is_delete !=  ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['is_delete'];
        }

        //是否开票申请  add by loreta.cheng 2015-06-08     
        if(isset($arg_array['statusKp']) && !empty($arg_array['statusKp'])){
            $sql .= ' AND cai.`status` = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['statusKp'];
        }


        //拓展字段
        if (isset($arg_array['extend']) && !empty($arg_array['extend']) ) {

            $login_session =  $G_SHOP->sessionCache_get ( 'PS_LOGIN_SESSION' );
            $str_departmentID= strstr($arg_array['extend'],"(");
            $str_departmentID=str_replace('(',',',$str_departmentID) ;
            $str_departmentID=str_replace(')',',',$str_departmentID) ;

            if(strpos($str_departmentID,",".$login_session['department'].",")>-1){
                $str_departmentID=str_replace(','.$login_session['department'].',',',',$str_departmentID) ;
                $str_departmentID=trim($str_departmentID,',');

                if($G_SHOP->has_permission(70006)){

                    $str_departmentID=$str_departmentID.",".$login_session['department'];
                }
                $str_departmentID = trim($str_departmentID,',');
                if($str_departmentID==""){
                 //如果该用户所在的组和她目前申领单的组不在同一个大组，当前用户看不了她的申领单信息，只可以她的上级看 add  by loreta.cheng 2015-06-29 start
                 //实例化部门类
                 $sysDepartment = new sysDepartment();
                 //递归查询部门数据
                 $sysDepartment->searchDepartment($department_array,104);
                 $departmentIDold=$this->getCardDepartment( $G_SHOP->currentUserID );
                 if($sysDepartment->deep_in_array($login_session['department'],$department_array) && $departmentIDold  && $departmentIDold!=$login_session['department']){
                    $departmentResult=$sysDepartment->searchPdepartmentID($departmentIDold,$login_session['department'],$department_array);
                    if($departmentResult){
                      $sql.=" AND ( card_apply.apply_user_id='".$G_SHOP->currentUserID."' OR (card_apply.departmentID=".$login_session['department']." AND card_apply.apply_user_id='".$G_SHOP->currentUserID."') )";
                    }else{
                      $sql.= $arg_array['extend']; 
                    }
                 }else{
                   $sql.=" AND ( card_apply.apply_user_id='".$G_SHOP->currentUserID."' OR (card_apply.departmentID=".$login_session['department']." AND card_apply.apply_user_id='".$G_SHOP->currentUserID."') )";
                }
             
                //如果该用户所在的组和她目前申领单的组不在同一个大组，当前用户看不了她的申领单信息，只可以她的上级看 add  by loreta.cheng 2015-06-29 end
                    
                }else{
                    $sql.=" AND ( card_apply.apply_user_id='".$G_SHOP->currentUserID."' OR (card_apply.departmentID IN ( ".$str_departmentID." ) OR card_apply.departmentID=".$login_session['department']." ) )";
                }
            }else{
                $sql .= $arg_array['extend'];
            }
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量 update by loreta.cheng 2015-06-08 增加开票申请条件
                
                 $search_sql = 'SELECT COUNT(*) as nums FROM card_apply LEFT JOIN `card_apply_invoice` AS cai ON cai.`apply_id`=card_apply.`apply_id`'.$sql;
                 
                 $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                
                $item_count = $count_array[0]->nums;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY card_apply.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY card_apply.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡入库单信息
            $search_sql = ' SELECT DISTINCT card_apply.*,user_master.trueName,user_master.mobile,cai.status as statusKp FROM card_apply

            LEFT JOIN `card_apply_invoice` as cai ON cai.`apply_id`=card_apply.`apply_id` LEFT JOIN user_master ON user_master.userID=card_apply.apply_user_id ' . $sql.$sql_new;

           
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'apply_id' => $item->apply_id,
                    'apply_date' => $item->apply_date,
                    'get_card_type' => $item->get_card_type,
                    'customer_name' => $item->customer_name,
                    'company_id' => $item->company_id,
                    'company_name' => $item->company_name,
                    'linkman' => $item->linkman,
                    'contact_way' => $item->contact_way,
                    'departmentID' => $item->departmentID,
                    'departmentName' => $item->departmentName,
                    'apply_user_id' => $item->apply_user_id,
                    'apply_trueName'=>$item->trueName,
                    'apply_mobile'=>$item->mobile,
                    'total_amount' => $item->total_amount,
                    'invoice_amount' => $item->invoice_amount,
                    'returned_amount' => $item->returned_amount,
                    'send_card_time' => $item->send_card_time,
                    'status' => $item->status,
                    'invoice_status' => $item->invoice_status,
                    'returned_money_status' => $item->returned_money_status,
                    'remark' => $item->remark,
                    'card_total_num' => $item->card_total_num,
                    'is_delete' =>$item->is_delete,
                    'paymentID' =>$item->paymentID,
                    'paymentName' =>$item->paymentName,
                    'statusKp'=>$item->statusKp
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 获取当前用户在大客户中的部门信息
     * @param $arg_array
     * @author allen.qiang@fistforward.com 2015-06-15
     */
    public function getCardDepartment ( $userID ) {
        global $G_SHOP;

        //检查参数
        if (!$userID) {
            return array( 'code' => 400, 'message' => '用户不存在' );
        }
        
        $company_masterSql = "select departmentID from card_apply where apply_user_id = '".$userID."' LIMIT 1";
        $company_masterRe = $G_SHOP->DBCA->stmt_query($company_masterSql);
        if($company_masterRe){
            return $company_masterRe[0]->departmentID;
        }else{
           return null;
        }
    }

    /**
     * 修改某个用户对应的大客户的部门信息
     * @param $arg_array
     * @author allen.qiang@fistforward.com 2015-06-15
     */
    public function changeCardDepartment ( $arg_array ) {
        global $G_SHOP;

        //检查参数
        if (empty($arg_array['userID'])) {
            return array( 'code' => 400, 'message' => '用户不存在' );
        }
        if (empty($arg_array['departmentID'])) {
            return array( 'code' => 400, 'message' => '部门id不存在' );
        }
        if (empty($arg_array['departmentName'])) {
            return array( 'code' => 400, 'message' => '部门名称不存在' );
        }
        

        //查询该用户下是否存在大用户信息
        $com_array=array(
            'apply_user_id' => $arg_array['userID'],
            'departmentID' => $arg_array['departmentIDold'],
            'sortname' => 'createTime',
            'sortorder' => 'ASC',
            'page' => '1',
            'rp' => '1'
            );
        $com_result=$this->search($com_array);
        if(!empty($com_result)){
         $card_applySql = "UPDATE card_apply SET departmentID = '".$arg_array['departmentID']."',departmentName = '".$arg_array['departmentName']."' WHERE apply_user_id = '".$arg_array['userID']."'";
         $card_applyRe = $G_SHOP->DBCA->stmt_query($card_applySql);
         return true;
        }else{
           return false;
        }
    }


    /**
     * 添加、修改申领单
     *
     */
    public function editCardApply ( $arg_array ) {

        global $G_SHOP;

        quanli_include('module/base/company/companyMaster.class.php');
        quanli_include('module/base/system/sysDepartment.class.php');

        $companyMaster = new companyMaster();

        //实例化部门类
        $sysDepartment = new sysDepartment();
        //获取回款名称
        //获取回款方式
        $backStr = $arg_array['apply_base']['backPay'];
        $backSql="select itemID,itemName from  sys_item  WHERE itemID in( $backStr)";
        $backArray=$G_SHOP->DBCA->stmt_query($backSql);

        $nameStr='';
        foreach($backArray as $backName){
            $nameStr.=$backName->itemName.',';
        }
        //检查参数

        if (!isset($arg_array['creator']) || empty($arg_array['creator'])) {
            $arg_array['creator'] = '';
        }

        if (!isset($arg_array['apply_base']['get_card_type']) || !in_array($arg_array['apply_base']['get_card_type'], array(1, 2))) {
            return array( 'message'=>'请选择领卡方式', 'code'=> 400 );
        }

        if (!isset($arg_array['apply_base']['customer_name']) || empty($arg_array['apply_base']['customer_name'])) {
            return array( 'message'=>'客户名称不能为空', 'code'=> 400 );
        }

        if (!isset($arg_array['apply_base']['apply_date']) || empty($arg_array['apply_base']['apply_date'])) {
            return array( 'message'=>'申请日期不能为空', 'code'=> 400 );
        }

        if ($arg_array['apply_base']['get_card_type'] == 2) {
            if (!isset($arg_array['apply_base']['company_id']) || !quanli_is_int($arg_array['apply_base']['company_id'])) {
                return array( 'message'=>'请选择大客户', 'code'=> 400 );
            }
        } else {
            $arg_array['apply_base']['company_id'] = '';
        }

        if (!isset($arg_array['apply_base']['linkman'])) {
            $arg_array['apply_base']['linkman'] = '';
        }

        if (!isset($arg_array['apply_base']['contact_way'])) {
            $arg_array['apply_base']['contact_way'] = '';
        }

        if (!isset($arg_array['apply_base']['remark'])) {
            $arg_array['apply_base']['remark'] = '';
        }

        if (!isset($arg_array['card_detail']) || !is_array($arg_array['card_detail']) || empty($arg_array['card_detail'])) {
            return array( 'message'=>'请录入现金卡信息信息', 'code'=> 400 );
        }

        if (!isset($arg_array['apply_base']['apply_id']) || !quanli_is_int($arg_array['apply_base']['apply_id'])) {
            $arg_array['apply_base']['apply_id'] = 0;
        }

        $apply_id = $arg_array['apply_base']['apply_id'];
        $get_card_type = $arg_array['apply_base']['get_card_type'];
        $customer_name = $arg_array['apply_base']['customer_name'];
        $apply_date = $arg_array['apply_base']['apply_date'];
        $company_id = $arg_array['apply_base']['company_id'];
        $linkman = $arg_array['apply_base']['linkman'];
        $contact_way = $arg_array['apply_base']['contact_way'];
        $remark = $arg_array['apply_base']['remark'];
        $total_amount = 0;
        $card_total_num = 0;

        try {

            $G_SHOP->DBCA->beginTransaction();

            // 查询大客户信息
            if ($company_id) {

                $search_args_array = array(
                    'company_id' => $company_id
                );
                $company_array = $companyMaster->search( $search_args_array );
                if (!$company_array) {
                    throw new Exception('大客户信息没有找到', 404);
                }
                $customer_name = $company_array[0]['company_name'];

            }

            //查询当前用户部门信息
            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');
            $departmentID = $PS_LOGIN_SESSION['department'];//当前部门id
            $department_array = $sysDepartment->searchDepartmentDetail( $departmentID );


            $cardApply = new entity('card_apply') ;
            if ($apply_id == 0) {

                $cardApply->creator = $arg_array['creator'];
                $cardApply->apply_id = generate_seqno('seqno_card_apply');
                $cardApply->apply_user_id = $_REQUEST['creator'];

            } else {

                $cardApply->apply_id = $apply_id;
                if (!$G_SHOP->DBCA->fetch($cardApply)) {
                    throw new Exception('申领单信息没有找到', 404);
                }

                //删除申领单现金卡信息
                $delete_sql = 'DELETE FROM card_apply_detail WHERE apply_id = ? ';
                $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $apply_id);

            }

            //保存申领单信息
            $cardApply->apply_date = $apply_date;
            $cardApply->get_card_type = $get_card_type;
            $cardApply->customer_name = $customer_name;
            $cardApply->company_id = $company_id;
            $cardApply->linkman = $linkman;
            $cardApply->contact_way = $contact_way;
            $cardApply->status = 1;
            $cardApply->remark = $remark;
            $cardApply->departmentID = $department_array['departmentID'];
            $cardApply->departmentName = $department_array['departmentName'];
            $cardApply->paymentID = $backStr;//回款方式ID
            $cardApply->paymentName = $nameStr;//回款方式名称



            //保存现金卡信息
            foreach($arg_array['card_detail'] as $card_value){

                $cardApplyDetail = new entity('card_apply_detail');

                $cardApplyDetail->apply_id = $cardApply->apply_id;
                $cardApplyDetail->creator = $_REQUEST['creator'];
                $cardApplyDetail->face_value_id = $card_value['face_value_id'];
                $cardApplyDetail->face_value = $card_value['face_value'];
                // add by sunqiang 0416
                $cardApplyDetail->card_type_id = $card_value['card_type_id'];
                $cardApplyDetail->card_type =  $card_value['card_type'];
                $cardApplyDetail->card_spec_id = $card_value['card_spec_id'];
                $cardApplyDetail->card_spec = $card_value['card_spec'];
                $cardApplyDetail->card_num = $card_value['card_num'];
                $cardApplyDetail->card_discount = $card_value['card_discount'];
                $cardApplyDetail->card_total_amount = $card_value['card_total_amount'];
                $cardApplyDetail->remark = $card_value['card_remark'];

                $total_amount += $card_value['card_total_amount'];
                $card_total_num += $card_value['card_num'];

                $G_SHOP->DBCA->save( $cardApplyDetail ) ;

            }

            $cardApply->total_amount = $total_amount;
            $cardApply->card_total_num = $card_total_num;
            $G_SHOP->DBCA->save( $cardApply ) ;

            $G_SHOP->DBCA->commit();

            if ($apply_id > 0) {
                return array( 'code' => 200, 'message' => '申领单修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '申领单保存成功' );
            }

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }
    }

    /**
     * 删除申领单信息方式
     * @param array $pay_array 申领单ID数组
     * @return array
     */
    public function deleteCardApply ( $pay_array ) {

        global $G_SHOP;

        if (!isset($pay_array) || !is_array($pay_array) || empty($pay_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //删除申领单信息 改变is_delete字段
            $card_apply_obj = new entity('card_apply');
            $card_apply_obj->apply_id = $pay_array['apply_id'];
            if (!$G_SHOP->DBCA->fetch( $card_apply_obj )) {
                throw new Exception('申领单映射信息没有找到', 404);
            }
            $card_apply_obj->is_delete = 1;
            $G_SHOP->DBCA->save( $card_apply_obj );

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '删除申领单信息成功' );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 现金卡信息新增类
     *
     */

    public function searchCardApplyDetail( &$arg_array ){

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申请编号
        if ( isset($arg_array['apply_id']) && is_numeric($arg_array['apply_id']) ) {
            $sql .= ' AND apply_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['apply_id'];
        }

        //现金卡面值id
        if ( isset($arg_array['face_value_id']) && is_numeric($arg_array['face_value_id']) ) {
            $sql .= ' AND face_value_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['face_value_id'];
        }

        //现金卡规格id
        if ( isset($arg_array['card_spec_id']) && is_numeric($arg_array['card_spec_id']) ) {
            $sql .= ' AND card_spec_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_spec_id'];
        }

        //现金卡数量
        if ( isset($arg_array['card_num']) && is_numeric($arg_array['card_num']) ) {
            $sql .= ' AND card_num = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_num'];
        }

        //现金卡折扣
        if ( isset($arg_array['card_discount']) && is_numeric($arg_array['card_discount']) ) {
            $sql .= ' AND card_discount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_discount'];
        }

        //现金卡总金额
        if ( isset($arg_array['card_total_amount']) && is_numeric($arg_array['card_total_amount']) ) {
            $sql .= ' AND card_total_amount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['card_total_amount'];
        }

        //现金卡备注
        if ( isset($arg_array['remark']) && is_numeric($arg_array['remark']) ) {
            $sql .= ' AND remark = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['remark'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply_detail ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询现金卡入库单信息
            $search_sql = 'SELECT * FROM card_apply_detail ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid'  => $item->uuid,
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'apply_id' => $item->apply_id,
                    'face_value_id' => $item->face_value_id,
                    'face_value' => $item->face_value,
                    'card_type_id' => $item->card_type_id,
                    'card_type' => $item->card_type,
                    'card_spec_id' => $item->card_spec_id,
                    'card_spec' => $item->card_spec,
                    'card_num' => $item->card_num,
                    'send_card_num' => $item->send_card_num,
                    'card_discount' => $item->card_discount,
                    'card_total_amount' => $item->card_total_amount,
                    'remark' => $item->remark

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 申领单信息开票类
     *
     */

    public function searchCardApplyInvoice( &$arg_array ){

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申请编号
        if ( isset($arg_array['apply_id']) && is_numeric($arg_array['apply_id']) ) {
            $sql .= ' AND apply_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['apply_id'];
        }

        //发票编号
        if ( isset($arg_array['invoice_id']) && is_numeric($arg_array['invoice_id']) ) {
            $sql .= ' AND invoice_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['invoice_id'];
        }

        //发票金额
        if ( isset($arg_array['invoice_amount']) && is_numeric($arg_array['invoice_amount']) ) {
            $sql .= ' AND invoice_amount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['invoice_amount'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply_invoice ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡入库单信息
            $search_sql = 'SELECT * FROM card_apply_invoice ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid'  => $item->uuid,
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'apply_id' => $item->apply_id,
                    'invoice_id' => $item->invoice_id,
                    'invoice_no' => $item->invoice_no,
                    'invoice_title' => $item->invoice_title,
                    'invoice_amount' => $item->invoice_amount,
                    'invoice_content' => $item->invoice_content,
                    'status' => $item->status,
                    'invoice_time' => $item->invoice_time,
                    'rcwflg' => $item->rcwflg,
                    'remark' => $item->remark

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 审核申领单
     * @param int $apply_id 申领单ID
     * @return array
     * @throws Exception
     */
    public function auditCardProduct( $apply_id ) {

        global $G_SHOP;

        if( !is_numeric($apply_id) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        /**
         * 申领单状态：1:申请中   2：已审核   3: 已发卡  4:已回款
         */

        try{
            $G_SHOP->DBCA->beginTransaction();

            //查询生产单信息
            $card_master = new entity('card_apply');

            $card_master->apply_id = $apply_id;

            if( !$G_SHOP->DBCA->fetch( $card_master ) )

                throw new Exception('没有找到申领单信息',404  );

            if( $card_master->status != 1 )

                throw new Exception('您当前页面已过期，请刷新页面',404  );
//            if ($card_master->card_status == 2) {
//                //重复审核\
//                throw new Exception('此代金卡已经审核过,请刷新页面!',404  );
//
//            }

            $card_master->status = 2;

            $G_SHOP->DBCA->save($card_master);

            $G_SHOP->DBCA->commit();
            return array( 'code' => 200, 'message' => '审核成功' );

        }catch (Exception $e){
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0){
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            }else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }


    /**
     * 申领单发卡
     * @param array $args_array
     * @return array
     */
    public function tuckCard( $args_array ) {

        global $G_SHOP;

        quanli_include('module/base/company/cardDetail.class.php');

        if( !isset($args_array['apply_id']) || !quanli_is_int($args_array['apply_id']) ) {
            return array( 'code' => 400 , 'message' => '参数错误' );
        }

        if (!isset($args_array['card_detail']) || !is_array($args_array['card_detail']) || empty($args_array['card_detail'])) {
            return array( 'code' => 400 , 'message' => '请录入现金卡' );
        }

        //实例金卡详情类
        $cardDetail = new cardDetail();

        $total_card_num = 0; //发卡总数量

        $send_card_array = array(); //本次操作申领单现金卡发卡数量

        try {

            $G_SHOP->DBCA->beginTransaction();


            //查询申领单现金卡详情
            $card_args_array = array(
                'apply_id' => $args_array['apply_id']
            );
            $apply_card_detail_array = $this->searchCardApplyDetail( $card_args_array );
            if (!$apply_card_detail_array) {
                throw new Exception('申领单现金卡信息没有找到', 404);
            }

            foreach($args_array['card_detail'] as &$card) {

                //查询代金卡详情
                $card_args_array = array(
                    'extend' => sprintf(' AND card_no BETWEEN %s AND %s', $card['card_no_start'], $card['card_no_end'])
                );
                $card_detail_array = $cardDetail->searchCardDetail( $card_args_array );
                if (!$card_detail_array) {
                    throw new Exception('现金卡信息没有找到', 404);
                }

                //现金卡数量
                $card_num = 0;

                //循环代金卡，检查代金卡状态
                foreach($card_detail_array as &$card_detail) {
                    if ($card_detail['card_status'] == 5) {
                        throw new Exception(sprintf('现金卡：%s，已发卡', $card_detail['card_no']), 404);
                    }
                    if ($card_detail['card_status'] == 6) {
                        throw new Exception(sprintf('现金卡：%s，已使用', $card_detail['card_no']), 404);
                    }
                    if ($card_detail['card_status'] == 7) {
                        throw new Exception(sprintf('现金卡：%s，已作废', $card_detail['card_no']), 404);
                    }
                    $card_num++;
                }

                $total_card_num += $card_num;

                $is_match = 0;

                $discount = 0;

                //循环申领单现金卡，检查录入的现金卡是否匹配
                foreach($apply_card_detail_array as &$apply_card_detail) {

                    if ($card_num == 0) {
                        continue;
                    }

                    $uuid = $apply_card_detail['uuid'];

                    //本次操作申领单现金卡发卡数量
                    $already_send_num = isset($send_card_array[$uuid]) ? $send_card_array[$uuid] : 0;

                    if ($apply_card_detail['face_value'] != $card_detail_array[0]['face_value']) {
                        continue;
                    }
                    if ($apply_card_detail['card_num'] - $apply_card_detail['send_card_num'] - $already_send_num < $card_num) {
                        continue;
                    }

                    $is_match = 1;
                    $G_SHOP->DBCA->stmt_query('UPDATE card_apply_detail SET send_card_num = send_card_num + ? WHERE uuid = ?', 'is', $card_num, $uuid);

                    $discount = round($apply_card_detail['card_total_amount'] / ($apply_card_detail['face_value'] * $apply_card_detail['card_num']), 4);

                    if (isset($send_card_array[$uuid])) {
                        $send_card_array[$uuid] += $card_num;
                    } else {
                        $send_card_array[$uuid] = $card_num;
                    }

                    break;

                }

                if ($is_match == 0) {
                    returnJsonData(sprintf('现金卡：%s ~ %s，与申领单现金卡不匹配', $card['card_no_start'], $card['card_no_end']), 404);
                }

                //更新现金卡状态
                $G_SHOP->DBCA->stmt_query('UPDATE card_detail SET card_status = 5, apply_id = ?, discount = ? WHERE card_no BETWEEN ? AND ?',
                                           'ssss', $args_array['apply_id'], $discount, $card['card_no_start'], $card['card_no_end']);

                //add by dongleixin 保存发卡日志 start
                /*=======================================================
               * 写入日志 start
               * ======================================================
               */
                quanli_include('module/base/customer/logHandler.class.php');
                //实例日志类
                $logHandler = new logHandler( $G_SHOP->DBCA );

                $log_array = array(
                    'logCategoryID' => 14,
                    'logItem' => $args_array['apply_id'],                     //申领单ID
                    'extend_1' => '发卡激活',
                    'extend_2' => $card['face_num'],                                   //发卡数量
                    'extend_5' => $card['face_value_id'],           //卡面值ID
                    'extend_7' => $card['face_value'],               //卡面面值
                    'extend_9' => $card['card_no_start'],                    //开始卡号
                    'extend_10' => $card['card_no_end'],                   //结束卡号
                    //'operator' => $G_SHOP->currentUserID
                    'operator' => $G_SHOP->currentUserName        //发卡人
                );

                $result_array = $logHandler->saveLogInfo( $log_array );

                if ($result_array['code'] != 200){
                    throw new Exception( $result_array['message'], 400);
                }
                /*=======================================================
                 * 写入日志 end
                 * ======================================================
                 */
                //add by dongleixin 保存发卡日志 end

            }

            //查询申领单信息
            $card_apply = new entity('card_apply');
            $card_apply->apply_id = $args_array['apply_id'];
            if( !$G_SHOP->DBCA->fetch( $card_apply ) ) {
                throw new Exception('没有找到申领单信息', 404);
            }
            if ( $card_apply->status == 1 ) {
                throw new Exception('此申领单未审核', 404);
            }
            if ( $card_apply->status == 3) {
                throw new Exception('此申领单已发卡', 404);
            }
            $card_apply->send_card_num += $total_card_num;
            if ($card_apply->send_card_num == $card_apply->card_total_num) {
                $card_apply->status = 3;
                $card_apply->send_card_time = $G_SHOP->sys_datetime;
            }
            $G_SHOP->DBCA->save($card_apply);

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '发卡成功' );


        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0){
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            }else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 申领单开票
     * @param int $apply_id 申领单ID
     * @return array
     * @throws Exception
     */
    public function outInvoiceCard( $args_array ) {

        global $G_SHOP;

        if (!isset($args_array['apply_id']) || !is_numeric( $args_array['apply_id'] )) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($args_array['invoice']['invoice_amount']) || !is_money($args_array['invoice']['invoice_amount'])) {
            return array( 'code' => 400, 'message' => '开票金额不能为空' );
        }

        if (!isset($args_array['invoice']['invoice_title']) || empty($args_array['invoice']['invoice_title'])) {
            return array( 'code' => 400, 'message' => '开票抬头不能为空' );
        }

        if (!isset($args_array['invoice']['invoice_content']) || empty($args_array['invoice']['invoice_content'])) {
            return array( 'code' => 400, 'message' => '开票内容不能为空' );
        }

        $invoice_amount         = $args_array['invoice']['invoice_amount'];
        $invoice_title          = $args_array['invoice']['invoice_title'];
        $invoice_content        = $args_array['invoice']['invoice_content'];
        $remark                 = $args_array['invoice']['remark'];
        try {

            $G_SHOP->DBCA->beginTransaction();

            //判断申领单信息，并修改申领单状态
            $card_apply = new entity('card_apply');
            $card_apply->apply_id = $args_array['apply_id'];
            if ( !$G_SHOP->DBCA->fetch($card_apply) ) {
                throw new Exception('申领单信息没有找到', 404);
            }
            $card_apply->invoice_amount += $invoice_amount;
            if ($card_apply->invoice_amount > $card_apply->total_amount) {
                throw new Exception('开票总金额不能大于申领单金额', 404);
            }

//            if($card_apply->invoice_amount < $card_apply->total_amount){
//                $card_apply->invoice_status = 1;
//
//            }elseif ($card_apply->invoice_amount == $card_apply->total_amount) {
//                $card_apply->invoice_status = 2;
//            }

            $G_SHOP->DBCA->save( $card_apply );

            //保存开票信息
            $card_apply_invoice = new entity('card_apply_invoice');
            $card_apply_invoice->apply_id = $args_array['apply_id'];
            $card_apply_invoice->invoice_title = $invoice_title;
            $card_apply_invoice->invoice_amount = $invoice_amount;
            $card_apply_invoice->invoice_content = $invoice_content;
            $card_apply_invoice->remark = $remark;
            $card_apply_invoice->status = 1;
            $card_apply_invoice->invoice_time = $G_SHOP->sys_datetime;
            $G_SHOP->DBCA->save($card_apply_invoice);

            $invoice_id = $G_SHOP->DBCA->insert_id;

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '开票成功', 'data' => array( 'invoice_id' => $invoice_id ) );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }


    public function confirmInvoice( $args_array ) {

        global $G_SHOP;

        if (!isset($args_array['invoice_id'], $args_array['invoice_no']) || !quanli_is_int( $args_array['invoice_id'] )) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (empty($args_array['invoice_no'])) {
            return array( 'code' => 400, 'message' => '请输入发票编号' );
        }

        try {

            //保存开票信息
            $card_apply_invoice = new entity('card_apply_invoice');
            $card_apply_invoice->invoice_id = $args_array['invoice_id'];
            if (!$G_SHOP->DBCA->fetch($card_apply_invoice)) {
                throw new Exception('申领单发票没有找到', 404);
            }
            if ($card_apply_invoice->status == 2) {
                throw new Exception('申领单发票已确认', 404);
            }
            $card_apply_invoice->status = 2;
            $card_apply_invoice->invoice_no = $args_array['invoice_no'];
            $G_SHOP->DBCA->save($card_apply_invoice);



            //更改card_apply 状态
            $card_apply = new entity('card_apply');
            $card_apply->apply_id= $card_apply_invoice->apply_id;
            $G_SHOP->DBCA->fetch($card_apply);
            if($card_apply->invoice_amount < $card_apply->total_amount){
                $card_apply->invoice_status = 1;

            }elseif ($card_apply->invoice_amount == $card_apply->total_amount) {
                $card_apply->invoice_status = 2;
            }
            $G_SHOP->DBCA->save($card_apply);
            return array( 'code' => 200, 'message' => '发票确认成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 申领单信息回款类
     *
     */

    public function searchCardApplyReturnedMoney( &$arg_array ){

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //申请编号
        if ( isset($arg_array['apply_id']) && is_numeric($arg_array['apply_id']) ) {
            $sql .= ' AND apply_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['apply_id'];
        }

        //回款单id
        if ( isset($arg_array['returned_id']) && is_numeric($arg_array['returned_id']) ) {
            $sql .= ' AND returned_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['returned_id'];
        }

        //回款金额
        if ( isset($arg_array['returned_amount']) && is_numeric($arg_array['returned_amount']) ) {
            $sql .= ' AND returned_amount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['returned_amount'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM card_apply_returned_money ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询代金卡入库单信息
            $search_sql = 'SELECT * FROM card_apply_returned_money ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid'  => $item->uuid,
                    'creator'  => $item->creator,
                    'timeStamp'=> $item->timeStamp,
                    'createTime' => $item->createTime,
                    'apply_id' => $item->apply_id,
                    'returned_id' => $item->returned_id,
                    'returned_type_id' => $item->returned_type_id,
                    'returned_type_name' => $item->returned_type_name,
                    'returned_amount' => $item->returned_amount,
                    'is_confirm' => $item->is_confirm,
                    'confirm' => $item->confirm,
                    'confirm_time' => $item->confirm_time,
                    'remark' => $item->remark,
                    'backTime'=>$item->backTime //实际回款日期

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 申领单回款
     * @param int $apply_id 申领单ID
     * @return array
     * @throws Exception
     */
    public function returnedMoney( $args_array ) {

        global $G_SHOP;

        if (!isset($args_array['apply_id']) || !is_numeric( $args_array['apply_id'] )) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($args_array['returned_id']['returned_amount']) || !is_money($args_array['returned_id']['returned_amount'])) {
            return array( 'code' => 400, 'message' => '回款金额不能为空' );
        }

        if (!isset($args_array['returned_id']['returned_type_id']) || empty($args_array['returned_id']['returned_type_id'])) {
            return array( 'code' => 400, 'message' => '请选择回款方式' );
        }

        $returned_type_id               = $args_array['returned_id']['returned_type_id'];
        $returned_type_name             = $args_array['returned_id']['returned_type_name'];
        $returned_amount                = $args_array['returned_id']['returned_amount'];
        $remark                         = $args_array['returned_id']['remark'];
        $backTime                       = $args_array['returned_id']['backTime']; //实际回款日期

        try {

            $G_SHOP->DBCA->beginTransaction();

            //判断申领单信息，并修改申领单状态
            $card_apply = new entity('card_apply');
            $card_apply->apply_id = $args_array['apply_id'];
            if ( !$G_SHOP->DBCA->fetch($card_apply) ) {
                throw new Exception('申领单信息没有找到', 404);
            }
            $card_apply->returned_amount += $returned_amount;
            if ($card_apply->returned_amount > $card_apply->total_amount) {
                throw new Exception('回款金额不能大于申领单金额', 404);
            }

//            if($card_apply->returned_amount < $card_apply->total_amount){
//                $card_apply->returned_money_status = 1;
//
//            } elseif ($card_apply->returned_amount == $card_apply->total_amount) {
//                $card_apply->returned_money_status = 2;
//            }

            $G_SHOP->DBCA->save( $card_apply );

            //保存回款信息
            $card_apply_returned_money = new entity('card_apply_returned_money');
            $card_apply_returned_money->apply_id = $args_array['apply_id'];
            $card_apply_returned_money->creator = $_REQUEST['operator'];
            $card_apply_returned_money->returned_type_id = $returned_type_id;
            $card_apply_returned_money->returned_type_name = $returned_type_name;
            $card_apply_returned_money->returned_amount = $returned_amount;
            $card_apply_returned_money->is_confirm = 0;
            $card_apply_returned_money->confirm = $_REQUEST['operator'];
            $card_apply_returned_money->confirm_time = $G_SHOP->sys_datetime;
            $card_apply_returned_money->remark = $remark;
            $card_apply_returned_money->backTime = $backTime;
            $G_SHOP->DBCA->save($card_apply_returned_money);

            $returned_id = $G_SHOP->DBCA->insert_id;

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '回款成功', 'data' => array( 'returned_id' => $returned_id ) );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    //申领单确认回款
    public function confirmReturned( $args_array ) {

        global $G_SHOP;

        if (!isset($args_array['returned_id']) || !quanli_is_int( $args_array['returned_id'] )) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            //保存回款信息
            $card_apply_returned_money = new entity('card_apply_returned_money');
            $card_apply_returned_money->returned_id = $args_array['returned_id'];
            if (!$G_SHOP->DBCA->fetch($card_apply_returned_money)) {
                throw new Exception('申领单回款没有找到', 404);
            }
            if ($card_apply_returned_money->is_confirm == 1) {
                throw new Exception('申领单回款已确认', 404);
            }
            $card_apply_returned_money->is_confirm = 1;
            $G_SHOP->DBCA->save($card_apply_returned_money);


            //更改card_apply 状态
            $card_apply = new entity('card_apply');
            $card_apply->apply_id= $card_apply_returned_money->apply_id;
            $G_SHOP->DBCA->fetch($card_apply);
            if($card_apply->returned_amount < $card_apply->total_amount){
                $card_apply->returned_money_status = 1;

            } elseif ($card_apply->returned_amount == $card_apply->total_amount) {
                $card_apply->returned_money_status = 2;
            }
            $G_SHOP->DBCA->save($card_apply);







            return array( 'code' => 200, 'message' => '回款确认成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }
}